package cn.edu.scau.cmi.yanghongyu.dao;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.hibernate.Session;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import cn.edu.scau.cmi.ema.dao.AbstractJpaDao;

@Repository
@Transactional
public class FrontSpiderDAOImpl extends AbstractJpaDao implements FrontSpiderDAO {

	@PersistenceContext(unitName = "ema")
	private EntityManager entityManager;

	@Override
	public EntityManager getEntityManager() {
		return entityManager;
	}

	@Override
	public Set getTypes() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public boolean canBeMerged(Object o) {
		// TODO Auto-generated method stub
		return false;
	}

	//	获取没有检测的单条记录，用于逐条审核
	@Override
	public Map<String, String> getSingleMarklessCrawlerEvent() {
		HashMap<String, String> map = new HashMap<String, String>();

		Session session = entityManager.unwrap(Session.class);
		String sql = "SELECT * FROM spider WHERE is_check = 0 LIMIT 1";
		List list = session.createSQLQuery(sql).list();

		Object[] obj = (Object[]) list.get(0);

		map.put("id", String.valueOf(obj[0]));
		map.put("title", String.valueOf(obj[1]));
		map.put("href", String.valueOf(obj[2]));
		map.put("time", String.valueOf(obj[3]));
		map.put("author", String.valueOf(obj[4]));
		map.put("source", String.valueOf(obj[5]));
		map.put("mainContent", String.valueOf(obj[6]));

		return map;
	}

//	标记爬取的新闻是否是事件。
	@Override
	public boolean markCrawlerEvent(Long id, Integer isEma) {
		Session session = entityManager.unwrap(Session.class);
		String updateSql = "update spider " + "set is_ema = ?, is_check = 1 " + "where id = ?";
		int executeUpdate = session.createSQLQuery(updateSql).setInteger(0, isEma).setLong(1, id).executeUpdate();
		return executeUpdate == 1 ? true : false;
	}

	@Override
	public Map<String, String> getCrawlerEventById(Long id) {
		HashMap<String, String> map = new HashMap<String, String>();

		Session session = entityManager.unwrap(Session.class);
		String sql = "SELECT * FROM spider WHERE id = ?";
		List list = session.createSQLQuery(sql).setLong(0, id).list();

		Object[] obj = (Object[]) list.get(0);

		map.put("id", String.valueOf(obj[0]));
		map.put("title", String.valueOf(obj[1]));
		map.put("href", String.valueOf(obj[2]));
		map.put("time", String.valueOf(obj[3]));
		map.put("author", String.valueOf(obj[4]));
		map.put("source", String.valueOf(obj[5]));
		map.put("mainContent", String.valueOf(obj[6]));
		map.put("isEma", String.valueOf(obj[7]));

		return map;
	}
}